/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.document.controller;

import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.service.rpc.BeanService;
import com.je.common.base.util.MessageUtils;
import com.je.common.base.util.StringUtil;
import com.je.document.service.FileOperateFactory;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/je/document/bucket")
public class BucketController extends AbstractPlatformController {

    @Autowired
    private BeanService beanService;

    private Boolean checkIsDefault(DynaBean bean) {
        String isDefault = bean.getStr("is_default_bucket");
        String id = bean.getStr("je_document_bucket_id");
        if (Strings.isNullOrEmpty(isDefault)) {
            return false;
        }
        //如果是默认的储存桶 校验是否已经存在默认的
        if ("1".equals(isDefault)) {
            List<DynaBean> dynaBeans = metaService.select("JE_DOCUMENT_BUCKET", ConditionsWrapper.builder().eq("is_default_bucket", "1").ne("je_document_bucket_id", id));
            if (dynaBeans != null && dynaBeans.size() > 0) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    @Override
    @RequestMapping(value = "/doUpdateList", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult doUpdateList(BaseMethodArgument param, HttpServletRequest request) {
        List<DynaBean> lists = beanService.buildUpdateList(param.getStrData(), param.getTableCode());
        List<Object> returnList = new ArrayList();
        for (DynaBean bean : lists) {
            String action = bean.getStr("__action__");
            String saveType = bean.getStr("save_type");
            String bucket = bean.getStr("bucket");
            String id = bean.getStr("je_document_bucket_id");
            if ("doInsert".equals(action)) {
                if (StringUtil.isNotEmpty(bucket)) {
                    DynaBean dynaBean = metaService.selectOne("JE_DOCUMENT_BUCKET", ConditionsWrapper.builder().eq("bucket", bucket));
                    if (dynaBean != null) {
                        return BaseRespResult.errorResult(MessageUtils.getMessage("document.bucket.bucket.exits", bucket));
                    }
                }
                Boolean haveDefault = checkIsDefault(bean);
                if (haveDefault) {
                    return BaseRespResult.errorResult("已经存在默认的存储桶！");
                }
                commonService.buildModelCreateInfo(bean);
                metaService.insert(bean);
                returnList.add(bean.getValues());
            } else {
                if (StringUtil.isNotEmpty(saveType)) {
                    DynaBean dynaBean = metaService.selectOne("JE_DOCUMENT_BUCKET", ConditionsWrapper.builder().eq("save_type", saveType));
                    if (dynaBean != null && !id.equals(dynaBean.getStr("je_document_bucket_id"))) {
                        return BaseRespResult.errorResult(MessageUtils.getMessage("document.bucket.saveType.exits", saveType));
                    }
                }
                if (StringUtil.isNotEmpty(bucket)) {
                    DynaBean dynaBean = metaService.selectOne("JE_DOCUMENT_BUCKET", ConditionsWrapper.builder().eq("bucket", bucket));
                    if (dynaBean != null && !id.equals(dynaBean.getStr("je_document_bucket_id"))) {
                        return BaseRespResult.errorResult(MessageUtils.getMessage("document.bucket.bucket.exits", bucket));
                    }
                }
                Boolean haveDefault = checkIsDefault(bean);
                if (haveDefault) {
                    return BaseRespResult.errorResult("已经存在默认的存储桶！");
                }
                commonService.buildModelModifyInfo(bean);
                metaService.update(bean);
                returnList.add(bean.getValues());
            }

        }
        JSONObject returnObj = new JSONObject();
        returnObj.put("rows", returnList);
        returnObj.put("totalCount", returnList.size());
        return BaseRespResult.successResult(returnObj, String.format("%s 条记录被更新", returnList.size()));
    }


    @RequestMapping(value = "/clearBeanCache", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult clearCache(HttpServletRequest request) {
        String saveType = getStringParameter(request, "saveType");
        if (Strings.isNullOrEmpty(saveType)) {
            return BaseRespResult.errorResult("请选择要清理的存储桶类型！");
        }
        String[] saveTypes = saveType.split(",");
        for (String type : saveTypes) {
            FileOperateFactory.clearBeanCacheByStr(type);
        }

        return BaseRespResult.successResult("操作成功！");
    }

}
